<?php

namespace App\Http\Services\common;

use Illuminate\Support\Facades\Log;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;

class JwtService
{
    /**
     * @param null $uid
     * @return string
     * 生成token
     */
    public static function createToken($uid = null)
    {
        $config = config('jwt.default');
        $signer = new Sha256();//加密规则
        $time = time();//当前时间
        $token = (new Builder())
            ->issuedBy($config['iss'])//签发人
            ->canOnlyBeUsedBy($config['aud'])//接收人
            ->identifiedBy($config['id'], true) //标题id
            ->issuedAt($time)//发出令牌的时间
            ->canOnlyBeUsedAfter($time) //生效时间(即时生效)
            ->expiresAt($time + $config['expire']) //过期时间
            ->with('uid', $uid) //用户id
            ->sign($signer, $config['sign']) //签名
            ->getToken(); //得到token
        return (string)$token;
    }

    /**
     * @param null $token
     * @return int|mixed
     * 验证token
     */
    public static function verifyToken($token = null)
    {
        $config = config('jwt.default');
        //检测是否接收到了token
        if (empty($token)) {
            return 0;
        }

        try {
            //转化为可以验证的token
            $token = (new Parser())->parse((string)$token);
            //验证基本设置
            $data = new ValidationData();
            $data->setIssuer($config['iss']);
            $data->setAudience($config['aud']);
            $data->setId($config['id']);

            if (!$token->validate($data)) {
                return 0;
            }
            //验证签名
            $signer = new Sha256();
            if (!$token->verify($signer, $config['sign'])) {
                return 0;
            }
            //验证通过，返回用户id
            return $token->getClaim('uid');
        } catch (\Exception $e) {
            // JWT解析失败，记录错误日志
            Log::error('JWT parsing failed: ' . $e->getMessage());
            return 0;
        }
    }
}
